# Create your views here.
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse, HttpResponseRedirect
from thesocialstockmarket.personalstock.models import *
from thesocialstockmarket.users.models import *
from thesocialstockmarket.recommendation.models import *
from thesocialstockmarket.recommendation.views import *
from thesocialstockmarket.personalstock.forms import *



@login_required
def trade(request,stock_name):
    stock = Stock.objects.get(stock_name = stock_name)
    useraccount = request.user.related_user
    try :
        fluct = Fluct.objects.filter(stock = stock).latest('date')
    except  Fluct.DoesNotExist :
        raise Http404        
    if request.method == 'POST':
        transactionform = TransactionForm(request.POST)
        if transactionform.is_valid():
            trade = transactionform.save(commit = False)
            amount = transactionform.cleaned_data['amount']
            trade.user = request.user
            trade.stock = stock
            
            if trade.type =='B' :
                try:
                    a = PerStock.objects.get(user= request.user,stock=stock)
                except PerStock.DoesNotExist:
                    a = PerStock(user = request.user, stock = stock)
                if  useraccount.credit >= float(amount)*fluct.price :
                    a.current_hold = float(a.current_hold) +float(amount)
                    a.save()
                    useraccount.credit = float(useraccount.credit)-float(amount)*float(fluct.price)
                    useraccount.save()
                    trade.save()
                else :
                    return HttpResponseRedirect("/personalstock/tradeerror")
                return HttpResponseRedirect("/personalstock/displaytrade")
            elif trade.type == 'S' :
                try:
                    a = PerStock.objects.get(user= request.user,stock=stock)
                except PerStock.DoesNotExist:
                    return HttpResponseRedirect("/personalstock/tradeerror")
                if a.current_hold >= float(amount):
                    a.current_hold = float(a.current_hold)-float(amount)
                    a.save()
                    useraccount.credit = float(useraccount.credit)+float(amount)*fluct.price
                    useraccount.save()
                    trade.save()
                else:
                    return HttpResponseRedirect("/personalstock/tradeerror")
                return HttpResponseRedirect("/personalstock/displaytrade")
    else:
        transactionform = TransactionForm()
    return render_to_response('personalstock/trade.html', 
                              {'s': stock ,
                               'fluct' : fluct,
                               'useraccount':useraccount,
                               'user': request.user,
                               'transactionform': transactionform})
    
    

@login_required
def perstockdetail(request):
    useraccount = request.user.related_user
    perstock = PerStock.objects.filter(user = request.user)
    
    return render_to_response('personalstock/perstockdetail.html',
                               {'user': request.user,
                                'useraccount': useraccount,
                                'perstock':perstock,
                                 })



@login_required
def displaytrade(request):
    useraccount = request.user.related_user
    return render_to_response('personalstock/displaytrade.html', {'user': request.user,
                                                                  'useraccount': useraccount,})

@login_required
def stockmanage(request,stock_name):
    stock = Stock.objects.get(stock_name = stock_name)
    a = PerStock.objects.get(user= request.user,stock=stock)
    useraccount = request.user.related_user
    if request.method == 'POST':
        pform = PerStockForm(request.POST)
        if pform.is_valid():
            perstockform = pform.save(commit = False)
            a.display = perstockform.display
            a.save()
            return HttpResponse("<p>you have changed successfully</p>" )
    else:
        pform = PerStockForm()
    return render_to_response('personalstock/stockmanage.html', {'user': request.user,
                                                                  'useraccount': useraccount,
                                                                  'pform':pform}) 
    
       
def tradeerror(request):
    return render_to_response('personalstock/tradeerror.html')
    
    
def comment(request,from_friend, stock_name):
    try:
        stock = Stock.objects.get(stock_name = stock_name)
    except Stock.DoesNotExist:
        raise Http404
    friend = User.objects.get(username = from_friend)
    perstock = PerStock.objects.get(stock = stock, user= friend)
    if request.method == 'POST': 
        form = PerStockRecForm(request.POST)
        if form.is_valid():
            perstockrec = form.save(commit = False)
            perstockrec.per_stock = perstock
            perstockrec.stock = stock
            perstockrec.user = request.user
            perstockrec.save()
            return HttpResponseRedirect("/personalstock/comment/%s/%s/" % (from_friend, stock_name))
    else:
        form = PerStockRecForm()
    rec = PerStockRec.objects.filter(stock = stock)
    
    try:
        has_rated = PerStockRec.objects.get(per_stock= perstock,user = request.user)
    except PerStockRec.DoesNotExist:
        has_rated =  None
    
    return render_to_response('personalstock/comment.html',
            {
             'perstock': perstock,
             's': stock,
             'form': form,
             'rec':rec,
             'user' :request.user,
             'has_rated':has_rated
             })
    
    
def rating(request,stock_name,id):
    try:
        stock = Stock.objects.get(stock_name = stock_name)
    except Stock.DoesNotExist:
        raise Http404
    
    rec = PerStockRec.objects.get(id = id)

    rec_rat = PerStockRecRating.objects.filter(per_stock_rec = rec)
    if request.method == 'POST': 
        form = PerStockRecRatingForm(request.POST)
        if form.is_valid():
            perstockrating = form.save(commit = False)
            perstockrating.user = request.user
            perstockrating.per_stock_rec = rec
            perstockrating.save()
            return HttpResponseRedirect("/personalstock/commentrating/%s/%s/" % ( stock_name,id))
    else:
        form = PerStockRecRatingForm()
    try:
        has_rated = PerStockRecRating.objects.get(per_stock_rec = rec, user = request.user)
    except PerStockRecRating.DoesNotExist:
        has_rated =  None
    count = 0
    sum = 0
    avg_rat = 0.0
    for rat in rec_rat:
        sum += int(rat.rating)
        count += int(rat.per_stock_rec_id)
    
        if count is 0:
             avg_rat 
        else:
             avg_rat = float(sum / count)

    return render_to_response('personalstock/commentrating.html',
            {
             's': stock,
             'form': form,
             'rec':rec,
             'user' :request.user,
             'has_rated':has_rated,
             'sum': sum, 
             'avg_rat': avg_rat,
             'count':count,
             })